package asdf.trial.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;


public class TcpClientHandler extends SimpleChannelInboundHandler<Object>
{

    private long timestamp;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg)
            throws Exception
    {
        String sMsg = ( (ByteBuf) msg ).toString(CharsetUtil.UTF_8).trim();
        //messageReceived方法,名称很别扭，像是一个内部方法.
        System.out.println("client接收到服务器返回的消息:" + sMsg);

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception
    {
        if ( evt instanceof IdleStateEvent ) {
            IdleStateEvent e = (IdleStateEvent) evt;
            switch ( e.state() ) {
                case WRITER_IDLE:
                    if ( ( System.currentTimeMillis() - timestamp ) > 3000 ) {
                        timestamp = System.currentTimeMillis();
                        ctx.writeAndFlush(
                                Unpooled.wrappedBuffer("ping".getBytes(CharsetUtil.UTF_8)));
                    }
                    break;
                default:
                    break;
            }
        }

    }


}

